package com.lanling.redis.client.util;

import com.lanling.redis.client.protocol.Protocol;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.exceptions.JedisException;

import java.io.UnsupportedEncodingException;

/**
 * @date ：Created in 2021/11/23 9:34
 * @description：编码转换
 * @author：lanling
 */
public class SafeEncoder {
    /**
     * 字符串转byte
     * @param str
     * @return
     */
    public static byte[] encode(final String str) {
        try {
            if (str == null) {
                throw new JedisDataException("value sent to redis cannot be null");
            }
            return str.getBytes(Protocol.CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new JedisException(e);
        }
    }

    /**
     * byte转字符串
     * @param data
     * @return
     */
    public static String encode(final byte[] data) {
        try {
            return new String(data, Protocol.CHARSET);
        } catch (UnsupportedEncodingException e) {
            throw new JedisException(e);
        }
    }
}
